require(['init'], function () {
  var $pagination = $('#js-pagination');
  var pagination;
  var $listTable = $('#js-userlist')

  function User(options) {
    options = options || {};
    this.data = options.data || this.getDefaultData();
    this.$dom = $('<div class="formList"></div>');

    this.init(this.configList);
  }

  User.prototype = {
    configList: [
      {
        title: i18next.t('table.account'),//账号
        content: {
          init: function ($content, root) {
            root.$nameInput = $('<input type="text" class="form-control" style="width: 200px">').appendTo($content);
            root.$nameInput.on('change', function () {
              root.data.account = $.trim(root.$nameInput.val());
            })
          },
          update: function ($content, root, formData) {
            if(formData.account) {
              root.$nameInput.val(formData.account)
            }
          }
        }
      },
      {
        title: i18next.t('table.mobilephone'),//手机
        content: {
          init: function ($content, root) {
            root.$phoneInput = $('<input type="text" class="form-control" style="width: 200px">').appendTo($content);
            root.$phoneInput.on('change', function () {
              root.data.number = $.trim(root.$phoneInput.val());
            })
          },
          update: function ($content, root, formData) {
            if(formData.number) {
              root.$phoneInput.val(formData.number).attr('disabled', 'disabled')
            }
          }
        }
      },
      {
        title:  i18next.t('info.email'),//'邮箱',
        content: {
          init: function ($content, root) {
            root.$emailInput = $('<input type="text" class="form-control" style="width: 200px">').appendTo($content);
            root.$emailInput.on('change', function () {
              root.data.email = $.trim(root.$emailInput.val());
            })
          },
          update: function ($content, root, formData) {
            root.$emailInput.val(formData.email)
          }
        }
      },
      {
        title: i18next.t('table.password'),
        content: {
          init: function ($content, root) {
            root.$passInput = $('<input type="password" class="form-control" data-formcheck="length" style="width: 200px">').appendTo($content);
            root.$passInput.on('change', function () {
              root.data.password = $.trim(root.$passInput.val());
            })
          },
          update: function ($content, root, formData) {
            // root.$passInput.val(formData.password)
          }
        }
      },
      {
        title: i18next.t('table.repeatpassword'),
        content: {
          init: function ($content, root) {
            root.$repassInput = $('<input type="password" class="form-control" data-formcheck="length" style="width: 200px">').appendTo($content);
            root.$repassInput.on('change', function () {
              root.data.repassword = $.trim(root.$repassInput.val());
            })
          },
          update: function ($content, root, formData) {
            // root.$passInput.val(formData.repassword)
          }
        }
      },
      {
        title:i18next.t('table.enabledstate') ,//'启用状态'
        content: {
          init: function ($content, root) {
            root.$useCheck = $('<span class="icon icon-size-16 icon-checkbox checked" data-type="checkbox">\
                <input type="checkbox" name="use" data-checkedmax="1" checked value="1">\
            </span>').appendTo($content);
            root.$useCheck.on('change', function () {
              root.data.islock = root.$useCheck.find('input').prop('checked') ? 0: 1
            })
          },
          update: function ($content, root, formData) {
            if(formData.islock == 1) {
              root.$useCheck.find('[type="checkbox"]').prop('checked', false).parent().removeClass('checked')
            }
          }
        }
      }
    ],
    createFormLi: function (liConfig) {
      var $formLi = $('<div class="formLi"></div>').appendTo(this.$dom);
      $('<div class="formTitle"></div>').html('<span class="titleText">'+ liConfig.title +'</span>').appendTo($formLi);
      var $formContent = $('<div class="formContent"></div>').appendTo($formLi);
      liConfig.content.init($formContent, this);
      if(liConfig.content.update) {
        liConfig.content.update($formContent, this, this.data);
      }
    },

    init: function (liConfigList) {
      $.each(liConfigList, function (i, cur) {
        this.createFormLi(cur)
      }.bind(this));
    },
    getDefaultData: function () {
      return {
        islock: 0
      }
    }
  }

  function addCheckOption(obj, data, key) {
    if(data[key] != undefined) {
      obj[key] = data[key]
    }
  }

  function getUserList(query, cb) {
    var url = '/api/users'

    function activeBtn($parent, item) {
      var $activeBtn = $('<a><span class="btn btn-primary btn-sm btn-inverse">'+i18next.t('table.enabled')+'</span></a>').appendTo($parent)
      $activeBtn.on('click', function () {
        ajaxMethod({
          url: '/api/user/' + item.userid,
          method: 'put',
          data: {
            islock: 0
          },
          success: function(data, status) {
            if(status.code == 0) {
              pagination($pagination, getUserList)
            }
          }
        })
      })
    }



    function permissionBtn($parent, item) {
      var $wrapperDom = $('<div style="padding:20px"></div>')

      function loadAllRoles(data) {
        $wrapperDom.html('')
        $.each(data, function (i, role) {
          var $item = $('<div style="height:25px">\
            <span class="icon icon-size-16 icon-checkbox" data-type="checkbox">\
                <input id="id_'+ role.id +'" type="checkbox" name="gender">\
            </span><span data-type="label">'+ role.title +'</span>\
          </div>').appendTo($wrapperDom)
        })
      }

      function loadUserRoles(data) {
        $.each(data, function (i, item) {
          $wrapperDom.find('#id_'+ item.id +'').prop('checked', true).parent().addClass('checked')
        })
      }


      var $btn = $('<a><span class="btn btn-primary btn-sm btn-inverse">'+i18next.t('index.rolemanagement')+'</span></a>').appendTo($parent)
      $btn.on('click', function () {
        $.when(
          $.ajax('/api/authority/roles?status=1'),
          $.ajax('/api/authority/'+ item.userid +'/roles')
        ).done(function () {
          var cbFnArr = [
            loadAllRoles,
            loadUserRoles
          ]

          var resArr = [].slice.call(arguments,0,2)
          $.each(resArr, function (i, curRes) {
            if(curRes[1] == 'success') {
              cbFnArr[i](curRes[0].data)
            }
          })

          var popUpBox=new PopUpBox({
            type:'dom',
            style:'default contentScroll',
            submitBtnType:'confirm',
            titleText:i18next.t('table.edituserroles'),//编辑用户角色
            drag:true,
            show: true,
            content: $wrapperDom,
            callback:{
              yes: function (e) {
                var ids = []
                $wrapperDom.find('input:checked').each(function (i, item) {
                  ids.push(Number(this.id.split('_')[1]))
                })

                ajaxMethod({
                  url:  '/api/authority/userRoles',
                  method: 'post',
                  data: {
                    uid: item.userid,
                    roleids: ids
                  },
                  success: function (data, status) {
                    if(status.code == 0) {
                      pagination.updateData()
                      popUpBox.close()
                    }
                  }
                })
                return false;
              }
            },
            position:{
              width: 420,
              height: 450
            }
          })
        })

      })
    }

    function editBtn($parent, item) {
      var $editBtn = $('<a class="ml5"><span class="btn btn-primary btn-sm btn-inverse">'+i18next.t('table.compile')+'</span></a>').appendTo($parent)
      $editBtn.on('click', function () {
        var user = new User({
          data: {
            account: item.account,
            number: item.number,
            email: item.email,
            islock: item.islock
          }
        })

        var popUpBox=new PopUpBox({
          type:'dom',
          style:'default contentScroll',
          submitBtnType:'confirm',
          titleText:i18next.t('table.edituser'),//编辑用户
          drag:true,
          show: true,
          content: user.$dom,
          callback:{
            yes: function (e) {
              var checkOption = {}
              addCheckOption(checkOption, user.data, 'account')
              addCheckOption(checkOption, user.data, 'number')
              addCheckOption(checkOption, user.data, 'email')

              ajaxMethod({
                url: '/api/user/' + item.userid,
                method: 'put',
                data: $.extend(checkOption, {
                  password: user.data.password,
                  islock: user.data.islock
                }),
                success: function (data, status) {
                  if(status.code == 0) {
                    pagination.updateData()
                    popUpBox.close()
                  } else {
                    _Tips(status.message)
                  }
                }
              })

              return false;
            }
          },
          position:{
            width: 420,
            height: 450
          }
        })
      })
    }

    function deleteBtn($parent, item) {
      var $deleteBtn = $('<a href="javascript:;"><span class="btn btn-danger btn-sm btn-inverse">'+i18next.t('table.forbidden')+'</span></a>').appendTo($parent)
      $deleteBtn.on('click', function () {
        var popUpBox = new PopUpBox({
          type: 'dom',
          style: 'default contentScroll',
          submitBtnType: 'confirm',
          titleText: i18next.t('popupbox.systemmessages'),//系统消息
          show: true,
          content: '<div style="padding:30px">'+i18next.t('popupbox.forbiddenuser')+' </div>',
          callback: {
             yes: function (e) {
               ajaxMethod({
                 url: '/api/user/' + item.userid,
                 data: {
                   islock: 1
                 },
                 method: 'put',
                 success: function(data, status) {
                   if(status.code == 0) {
                     pagination($pagination, getUserList)
                   }
                 }
               })
             }
          },
          position: {
             width: 420,
             height: 200
          }
        })
      })
    }

    function showList($table,$pagination, data) {
      if(data.list.length == 0) {
        $table.html('<div style="margin-top:50px;text-align:center">'+i18next.t('input.nullresults')+'</div>')
        $pagination.hide()
        return
      }

      $table.html('')
      var $thead = $('<thead>\
        <tr>\
          <th>'+i18next.t('table.no')+'</th>\
          <th>'+i18next.t('table.account')+'</th>\
          <th>'+i18next.t('info.cellphonenumber')+'</th>\
          <th>'+i18next.t('info.email')+'</th>\
          <th>'+i18next.t('table.enabledstate')+'</th>\
          <th>'+i18next.t('table.accountStatus')+'</th>\
          <th>'+i18next.t('table.handle')+'</th>\
        </tr>\
      </thead>').appendTo($table)

      var $tbody = $('<tbody></tbody>').appendTo($table)
      $.each(data.list, function (i, item) {
        var $tr = $('<tr></tr>')
        $tr.append('<td>'+ (i+1) +'</td>')
        $tr.append('<td>'+ (item.account || '') +'</td>')
        $tr.append('<td>'+ (item.number||'') +'</td>')
        $tr.append('<td>'+ (item.email || '') +'</td>')
        $tr.append('<td><div class="'+ (item.islock?'text-danger':'text-primary') +'">'+ (item.islock?i18next.t('info.no'):i18next.t('info.yes')) +'</div></td>')
        var status='';
        switch(item.type){
          case 1:
                status='机构';
                break;
          case 2:
            status='老师';
            break;
          case 3:
            status=i18next.t('table.student');
            break;
          default:break;
        }
        $tr.append('<td>'+ status +'</td>')
        var $handleTd = $('<td></td>').appendTo($tr)
        if(item.islock) {
          $tr.addClass('disable')
          // activeBtn($handleTd, item)
        } else {
          // deleteBtn($handleTd, item)
        }

        editBtn($handleTd, item)
        // permissionBtn($handleTd, item)
        $tbody.append($tr)
      })
      $pagination.show()
    }

    ajaxMethod({
      url: url,
      data: query || {},
      success: function (data) {
        cb && cb(data)
        showList($listTable,$pagination, data)
      }
    })
  }

  function loadSearchData(querystr) {
    if(querystr) {
      pagination.filter.email = querystr
      pagination.filter.account = querystr
      pagination.filter.number = querystr

      pagination.searchData()
    } else {
      pagination.reloadData()
    }
  }


  $('#J_search').on('click', function() {
    var $input = $(this).prev();
    var querystr = $.trim($input.val());
    loadSearchData(querystr)
  })

  $('.searchInput').on('keyup', function(e) {
    if(e.keyCode == 13) {
      var querystr = $.trim($(this).val());
      loadSearchData(querystr)
    }
  })

  pagination = new Pagination($pagination, getUserList)


  function checkHandle(user, checkOption, cb) {
    ajaxMethod({
      url: '/api/user/check',
      method: 'post',
      data: checkOption,
      success: function (data, status) {
        if(data && (data instanceof Array)) {
          $.each(data, function (i, item) {
            switch (item) {
              case 'account':
                FormCheck.checkTips(user.$nameInput, {
                  status: false,
                  result: i18next.t('table.accountexistence'),
                  followTips: true
                })
                break;
              case 'email':
                FormCheck.checkTips(user.$emailInput, {
                  status: false,
                  result: i18next.t('table.emailexistence'),
                  followTips: true
                })
                break;
              case 'number':
                FormCheck.checkTips(user.$phoneInput, {
                  status: false,
                  result: i18next.t('table.phoneexistence'),
                  followTips: true
                })
                break;
            }
          })
          return;
        }
        cb && cb()

      }
    })
  }


  $('#js-adduser').on('click', function () {
    var user = new User()
    var popUpBox=new PopUpBox({
      type:'dom',
      style:'default contentScroll',
      submitBtnType:'confirm',
      titleText:i18next.t('table.adduser'),//添加用户
      drag:true,
      show: true,
      content: user.$dom,
      callback:{
        yes: function (e) {
          if(user.data.account == undefined && user.data.number == undefined && user.data.email == undefined ) {
            _Tips(i18next.t('table.import'))//'请输入账号、手机、邮箱中的至少一项'
            return false
          }

          var checkOption = {}
          addCheckOption(checkOption, user.data, 'account')
          addCheckOption(checkOption, user.data, 'number')
          addCheckOption(checkOption, user.data, 'email')

          checkHandle(user, checkOption, function () {
            var formCheckResult = FormCheck.childrenInputCheck(user.$dom)
            if(formCheckResult) {
              if(user.data.password !== user.data.repassword) {
                _Tips(i18next.t('table.twice'))
                return
              }
              ajaxMethod({
                url: '/api/user',
                method: 'post',
                data: $.extend(checkOption, {
                  password: user.data.password,
                  islock: user.data.islock
                }),
                success: function (data, status) {
                  if(status.code == 0) {
                    pagination.updateData()
                    popUpBox.close()
                  }
                }
              })
            }
          })
          return false;
        }
      },
      position:{
        width:420,
        height:450
      }
    })
  })

})
